package cn.hzc.fortess.system.controller;

import cn.hzc.fortess.core.common.BizErrorEnum;
import cn.hzc.fortess.core.common.ResponseData;
import cn.hzc.fortess.core.common.annotion.RequestPermission;
import cn.hzc.fortess.core.common.exception.ServiceException;
import cn.hzc.fortess.system.entity.Menu;
import cn.hzc.fortess.system.entity.ResourceAttr;
import cn.hzc.fortess.system.service.MenuService;
import cn.hzc.fortess.system.service.ResourceAttrService;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 菜单数据字段
 */
@Api(tags = {"菜单资源属性管理","数据权限管理"})
@Controller
@RequestMapping("/sam/resource")
public class ResourceController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(ResourceController.class);


    @Autowired
    private MenuService menuService;
    @Autowired
    private ResourceAttrService resourceAttrService;


    @ApiIgnore
    @RequestMapping(value = "",method = RequestMethod.GET)
    public String index() {
        throw new ServiceException(BizErrorEnum.REQUEST_NULL);
    }


    @ApiIgnore
    @RequestMapping(value = "/{menuId}")
    public String index(@PathVariable(value = "menuId") Integer menuId, Model model) {
        Menu menu = menuService.getById(menuId);
        model.addAttribute("menuName", menu.getResourceName());
        model.addAttribute("menuId", menu.getId());
        return buildToView("index.html");
    }

    @ApiOperation("获取菜单的字段属性列表")
    @ResponseBody
    @RequestMapping(value = "/list/{menuId}",method = RequestMethod.POST)
    public ResponseData list(@PathVariable(value = "menuId") Integer menuId) {
        List<ResourceAttr> attrs = this.resourceAttrService.getMenuResourceAttrList(menuId);
        if (!CollectionUtils.isEmpty(attrs)) {
            attrs.parallelStream().forEach(resourceAttr -> {
                resourceAttr.setCreateTime(null);
                resourceAttr.setCreateUser(null);
                resourceAttr.setUpdateTime(null);
                resourceAttr.setUpdateUser(null);
            });
        }
        final ResponseData response = new ResponseData();
        response.setData(attrs);
        return response;
    }

    /**
     * 保存菜单的数据
     */
    @ApiOperation("批量保存菜单的字段属性")
    @RequestMapping(value = "/save.json",method = RequestMethod.POST)
    @ResponseBody
    @RequestPermission(value = {"sam:menu:add", "sam:menu:edit"}, logical = Logical.OR)
    public ResponseData save(@RequestParam("data") String attrs, @RequestParam("menuId") Integer menuId) {

        log.info("保存菜单字段属性数据:{},menuId:{}",attrs,menuId);
        if (StringUtils.isBlank(attrs)) {
            resourceAttrService.save(menuId, Lists.newArrayList());
            return ResponseData.success();
        }
        String[] data = attrs.split("\\|");
        final List<ResourceAttr> list = Lists.newArrayList(data).parallelStream().filter(tmp -> StringUtils.isNotBlank(tmp)).map(tmp -> buildResourceAttr(tmp)).collect(Collectors.toList());
        resourceAttrService.save(menuId, list);
        return ResponseData.success();
    }

    private ResourceAttr buildResourceAttr(String attrStr) {
        String[] attrArray = attrStr.split(",");
        final ResourceAttr resourceAttr = new ResourceAttr();
        //  id,attrCode,attrName,idx,resourceId
        resourceAttr.setId("-1".equals(attrArray[0]) ? null : Integer.parseInt(attrArray[0]));
        resourceAttr.setAttrCode(attrArray[1]);
        resourceAttr.setAttrName(attrArray[2]);
        resourceAttr.setIdx(NumberUtils.isDigits(attrArray[3]) ? Integer.parseInt(attrArray[3]) : 100);
        resourceAttr.setResourceId(Integer.parseInt(attrArray[4]));
        return resourceAttr;


    }


    @Override
    protected String moduleName() {
        return "resource";
    }
}
